#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
<<<<<<< HEAD
@File Name  : c_book.py
=======
@File Name  : text.py
@Author     : LeeCQ
@Date-Time  : 2019/11/30 19:41

"""

import requests
from root_class import Root9C
from c_mysql import MySQL9C


class Book9C(Root9C):
    """
    获取小说；
        txt文件结构 -
        【{'a_id',       id
           'a_name',    name
           'a_pic',     a picture
           'a_remarks', 简介
           'a_type',    分类编码
           'a_time'     时间
        }】
    """
    DIR_BOOK_ROOT = Root9C.DIR_ROOT + 'txt/'

    def __init__(self):
        self.book_tags = [_t for _t in self.txt2tag() if _t[0] == 'book_list']
        self.book_api = self.get_api_book()
        self._sql = MySQL9C()

    def connect_SQL(self):
        self._sql = MySQL9C()

    def get_json_book(self):
        return [{_t[1]: self.json_one_txt(self.DIR_SUP + _t[2])} for _t in self.book_tags]

    def get_json_book_inOne(self):
        """不常用的 - 把所有的数据读取到一个列表中
        数据结构： 【{data}，】
        """
        return self.json_all_txt([self.DIR_SUP + p[2] for p in self.book_tags])

    def get_api_book(self):
        """ 取得Book_Api的地址 -- 通过 a_id 参数 """
        return 'http:/' + self.api_()['txtapi'].replace('//', '/')

    def get_text(self, a_id):
        txt_header = {
            'Accept': 'text/html, application/xhtml+xml, application/xml; q=0.9, */*; q=0.8',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-Hans-CN, zh-Hans; q=0.5',
            'Cache-Control': 'no-cache',
            'Connection': 'Keep-Alive',
            'Host': self.book_api.split('/')[2],
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362'
        }
        for i in range(3):
            _res = requests.get(self.book_api + a_id, headers=txt_header)
            if _res.status_code == 200:
                return _res.text
        return '404 Not Found!'

    def get_image(self, url):
        """"""
        pic_header = self.HEADER
        pic_header['Host'] = url.split('/')[2]
        for i in range(3):
            _res = requests.get(url, headers=pic_header)
            if _res.status_code == 200:
                return _res.content
        return None

    def save_a_book(self, a_dict):
        """
        下载一个txt
        :param dict a_dict: keys -> ('a_id', 'a_name', 'a_pic', 'a_remarks', 'a_type', 'a_time')
        :return txt_data
        """
        print(self.book_api+a_dict['a_id'])
        a_dict['a_pic'] = self.get_image(a_dict['a_pic'])
        while True:
            _temp = self.get_text(a_dict['a_id'])
            if not _temp.find(a_dict['a_remarks'][7:9]) == -1:
                a_dict['a_remarks'] = _temp
                return self._sql.book_append(**a_dict)
        # return self._sql.book_append(_id=a_dict['a_id'],
        #                              _name=a_dict['a_name'],
        #                              _pic=a_dict['a_pic'],
        #                              _remakes=a_dict['a_remakes'],
        #                              _time=a_dict['a_time'],
        #                              _type=a_dict['a_time']
        #                              )

    def save_books_inOne(self):
        for a_dict in self.get_json_book_inOne():
            print(a_dict)
            self.save_a_book(a_dict)

    def save_books(self):
        """"""
        for kind_ in self.get_json_book():
            for kind, txt_dict in kind_.items():
                for a_dict in txt_dict:
                    print(a_dict)
                    self.save_a_book(a_dict)


class TestBook(Book9C):
    def save_a_book(self, a_dict):
        pic_header = self.HEADER
        pic_header['Host'] = a_dict['a_pic'].split('/')[2]
        txt_header = {
            'Accept': 'text/html, application/xhtml+xml, application/xml; q=0.9, */*; q=0.8',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-Hans-CN, zh-Hans; q=0.5',
            'Cache-Control': 'no-cache',
            'Connection': 'Keep-Alive',
            'Host': 'txt.ks453.com',  # 可修改
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362'
        }
        print(self.book_api + a_dict['a_id'])
        a_dict['a_pic'] = requests.get(a_dict['a_pic'], headers=txt_header).content
        open('./sup/test.txt', 'w', encoding='utf8').write(
            self.get_text(a_dict['a_id'])
        )
        open('./sup/' + 'test.jpg', 'wb').write(a_dict['a_pic'])
        print('ok')

    def save_books(self):
        """"""
        for a_dict in self.get_json_book_inOne():
            print(a_dict)
            self.save_a_book(a_dict)


if __name__ == '__main__':
    dic = {'a_id': '477',
           'a_name': '那一晚上了学姐和大嫂',
           'a_pic': 'http://wmxz.img.qiaomeigift.com/681/1.jpg',
           'a_remarks': '\u3000“李晴川，今天你必死无疑。”猛烈爆炸声下，一名青年拉着一名冰冷少女，带领无数人马涌到舰首。\u3000\u3000“呵呵，就算是死，我也不会死在你们手里。”青年满身鲜血，纵身投向背后汹涌大海。\u3000\u3000“他跑了!”有人发出一',
           'a_type': '19',
           'a_time': '2019-09-30 00:10'}
    Book9C().save_books_inOne()
    # TestBook().save_bo(dic)
    # TestBook().save_books()
from root_class import Root9C


class Text9C(Root9C):
    """
    获取小说；
    """
    def __init__(self):
        self.text_tags = [_t for _t in self.txt2tag() if _t[0] == 'text_list']
